<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="https://www.w3cways.com/demo/vconsole/vconsole.min.js?v=2.2.0"></script>
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
	<script type="text/javascript">
		var statusBarHeight,pixelRatio,screenWidth,screenHeight,pixelHeight,pixelWidth,systemPlatform,currentDeviceId,currentDeviceName,isScanning=false,stopTimerObject;
		var serviceUuid='0000FF0A-0000-1000-8000-00805F9B34FB',writeUuid='0000FF08-0000-1000-8000-00805F9B34FB',notifyUuid='0000FF09-0000-1000-8000-00805F9B34FB';
    	//获取手机信息的回调接口
        function getSystemInfoCallback(resultStr){
            var jsonObject=JSON.parse(resultStr);
            systemPlatform=jsonObject['platform'];//获取手机操作系统
            screenWidth=window.screen.width;
            screenHeight=window.screen.height;
            pixelHeight=jsonObject['screenHeight'];
            pixelWidth=jsonObject['screenWidth'];
            pixelRatio=Math.ceil(pixelHeight/screenHeight);//算出屏幕像素比
            console.log('获取了手机的设备的设备信息,现在获取手机的蓝牙状态');
            window.hilink.getBluetoothAdapterState('getBluetoothAdapterStateCallback');//获取手机蓝牙状态     
        }
        //notify传回信息的回调
        function notifyCallback(resultStr){
        	var jsonObject=JSON.parse(resultStr);
        	console.log(jsonObject['characteristicId']+'的notify传来了数据:'+jsonObject['data']);	
        	if(jsonObject['characteristicId'].toUpperCase()==notifyUuid){
        		switch(jsonObject['data'][3]){
        			case '0':
        				jsonObject['data'][7]=='1'?console.log('设置运动模式成功'):console.log('设置运动模式失败');
        				break;
        			case '3':
        				jsonObject['data'][7]=='1'?console.log('打开或关闭实时数据上传功能成功'):console.log('打开或关闭实时数据上传功能失败');
        				break;
        			case '9':
        				jsonObject['data'][11]=='1'?console.log('启动或停止运动成功'):console.log('启动或停止运动失败');
        				break;
        			case '1':
        				if(jsonObject['data'][2]=='4'){
        					var sportCount=parseInt(jsonObject['data'].substring(6,10),16);
        					var heartCount=parseInt(jsonObject['data'].substring(14,16),16);
        					console.log('返回的实时运动数据: 次数'+sportCount+' 心率:'+heartCount);
        					app.sportCount='运动次数:'+sportCount+'次';
        					app.heartCount='心率:'+heartCount;
        				}
        				break;
        		}
        	}
        }
        //获取导航栏高度的回调函数
    	function getStatusBarHeightCallback(resultStr){
    		var jsonObject=JSON.parse(resultStr);
    		statusBarHeight=jsonObject['statusBarHeight'];
    	}
    	//服务发现完成之后的回调
        function discoverdServiceCallback(resultStr){
            var jsonObject=JSON.parse(resultStr);
            if(jsonObject['errCode']==0){
            	console.log('服务发现成功');
            	var retCode=window.hilink.notifyBLECharacteristicValueChange (currentDeviceId, serviceUuid, notifyUuid, true);//开启notify
            	window.hilink.onBLECharacteristicValueChange('notifyCallback');//注册notify的回调  
            	window.hilink.writeBLECharacteristicValue(currentDeviceId, serviceUuid, writeUuid, 'FEA0020201', 'writeDataCallback');//设置运动模式为拉力绳
            }else{
            	console.log('发现服务失败,再去连接一次');              
            	window.hilink.createBLEConnection(currentDeviceId);
            }
        }      
        //连接状态发生改变的回调
        function connectStageChangeCallback(resultStr){
            var jsonObject=JSON.parse(resultStr);
            if(jsonObject['connected']){//如果连接成功
            	window.hilink.onBLEServicesDiscovered('discoverdServiceCallback');//注册发现完服务之后的回调,要在连接成功之后注册此回调才有用
            	console.log('连接成功');
            }else{//如果连接失败就继续去连接设备
            	console.log('连接断开,现再去连接一次');
            	window.hilink.createBLEConnection(currentDeviceId);
            }
        }
        //监听扫描设备的回调
        function scanCallback(resultStr){
			var jsonObject=JSON.parse(resultStr);
			for(var i=0,length=jsonObject.length;i<length;i++){
				console.log('扫描到一个设备的名称为:'+jsonObject[i].localName+' mac地址为:'+jsonObject[i].deviceId);
				if(systemPlatform=='Android'){//如果是android设备就直接比较mac地址就可以了
					if(jsonObject[i].deviceId==currentDeviceId&&isScanning){
						console.log('[android]扫描到目标设备，现在去连接');
						isScanning=false;//修改是否正在扫描的标志位
						window.clearTimeout(stopTimerObject);//停止定时停止扫描的定时任务
						window.hilink.stopBluetoothDevicesDiscovery();//先停止扫描
						window.hilink.onBLEConnectionStateChange('connectStageChangeCallback');//注册连接状态改变之后的回调
        				window.hilink.createBLEConnection(currentDeviceId);//连接设备
					}
				}else{//如果是ios设备不能直接拿mac地址就比较广播的设备名称
					if(jsonObject[i].localName==currentDeviceName){
						console.log('[ios]扫描到目标设备，现在去连接');
						isScanning=false;//修改是否正在扫描的标志位
						window.clearTimeout(stopTimerObject);//停止定时停止扫描的定时任务
						window.hilink.stopBluetoothDevicesDiscovery();//先停止扫描
						window.hilink.onBLEConnectionStateChange('connectStageChangeCallback');//注册连接状态改变之后的回调
        				window.hilink.createBLEConnection(currentDeviceId);//连接设备
					}
				}
			}
        }
    	//获取用户点击九宫格的设备的回调函数
        function getRegisteredCallback(resultStr){
        	var jsonObject=JSON.parse(resultStr);
        	currentDeviceId=jsonObject['deviceId'];
        	currentDeviceName=jsonObject['deviceName'];
        	console.log('用户点击的九宫格的设备名称为:'+currentDeviceName+' mac地址为:'+currentDeviceId);
        	window.hilink.stopBluetoothDevicesDiscovery();//先停止扫描
        	window.hilink.onBluetoothDeviceFound('scanCallback');//注册扫描设备的监听
        	isScanning=true;//修改是否正在扫描的标志位
        	window.hilink.startBluetoothDevicesDiscovery(null,systemPlatform=='Android'?true:false,null);//开始扫描设备
        	console.log('开始扫描周边设备是否有目标设备');
        	stopTimerObject=window.setTimeout(function(){//开启10之后停止扫描的定时任务
        		isScanning=false
        		window.hilink.stopBluetoothDevicesDiscovery();//先停止扫描
        		console.log('已经达到最大扫描时间，停止扫描');
        	}, 10000);
        }
        //写入数据之后完成的回调
    	function writeDataCallback(errCode){
			if(errCode==0)
				console.log('数据写入成功');
			else
				alert('数据写入失败(内部错误/系统错误)');
    	}
    	//监听手机蓝牙状态改变的回调函数
        function bluetoothAdapterStateChangeCallback(resultStr){
            var jsonObject=JSON.parse(resultStr);
            if(jsonObject['available'])//如果蓝牙打开了
                window.hilink.getCurrentRegisteredDevice('getRegisteredCallback');//获取用户点击的九宫格设备信息
            else//如果蓝牙还是没有打开
                var errCode=window.hilink.openBluetoothAdapter();//打开蓝牙
        } 
    	 //得知手机蓝牙状态的回调函数
        function getBluetoothAdapterStateCallback(resultStr){
            var jsonObject=JSON.parse(resultStr);
            if(jsonObject['available']){//如果蓝牙打开了
            	console.log('手机蓝牙已经打开,现在去获取用户点击的九宫格的设备信息');
            	window.hilink.getCurrentRegisteredDevice('getRegisteredCallback');//获取用户点击的九宫格设备信息
            } 
            else{//如果蓝牙未打开
            	console.log('手机蓝牙未打开，现在去打开蓝牙');
                window.hilink.onBluetoothAdapterStateChange('bluetoothAdapterStateChangeCallback');//注册蓝牙状态改变的监听
                var errCode=window.hilink.openBluetoothAdapter();//打开蓝牙    
            }
        }
        window.hilink.getSystemInfoSync ('getSystemInfoCallback');//获取手机的操作系统信息
    	window.hilink.modifyTitleBar(false, '#FFFFFF', '');//设置导航栏颜色
    	window.hilink.getStatusBarHeight('getStatusBarHeightCallback');//获取导航栏高度
	</script>
	<style type="text/css">
        .margin{
            margin-top:30%; 
        }
        .mySelect{
            height: 10%;
            font-size: 70px;
        }
        .mySelect select{
           width: auto;
           padding: 0;
           font-size: 70px;
           margin: 0;
           -webkit-appearance: none;
        }
		.myText{
			height: 10%;
			font-size: 70px;
		}
    </style>
</head>
<body>
	<div id="app">
	<center>
        <div class="margin mySelect">
            <span>运动方式:</span>
            <select v-model="selected" v-on:change="selectType">
            <option v-for="item in selectArray" v-bind:value="item.value">
                {{item.text}}
            </option>
        </select>
        </div>
		<div class="margin">
				<button type="button" style="width: 35%;height: 100px;margin-right: 10%;font-size: 50px" v-on:click="startSport">开始运动</button>
				<button type="button"  style="width: 35%;height: 100px;margin-left: 10%;font-size: 50px" v-on:click="stopSport">结束运动</button>
		</div>
		<div class="margin myText">
				<span >{{sportCount}}</span>
		</div>
		<div class="margin myText">
			<span >{{heartCount}}</span>
		</div>
	</center>
	</div>
	
	<script type="text/javascript">
		var app = new Vue({
  			el: '#app',
  			data: {
                selected: 1,//select选中的值
                selectArray:[
                    {text: '往后拉',value:1},
                    {text: '脚踩正拉',value:2},
                    {text: '脚踩反拉',value:3},
                    {text: '头顶推拉',value:4}
                ],
    			sportCount: '运动次数:',
    			heartCount: '心率:'
  			},
  			methods: {
    			startSport: function () {//点击开始运动之后的调用函数
     				 if(currentDeviceId!=null){
    					window.hilink.writeBLECharacteristicValue(currentDeviceId, serviceUuid, writeUuid, 'FEA30101', 'writeDataCallback');//打开数据上传功能
    					window.hilink.writeBLECharacteristicValue(currentDeviceId, serviceUuid, writeUuid, 'FEA90101', 'writeDataCallback');//开始运动
    				}
    			},
    			stopSport: function () {//点击停止运动之后的调用函数
     				 if(currentDeviceId!=null){
    					window.hilink.writeBLECharacteristicValue(currentDeviceId, serviceUuid, writeUuid, 'FEA30100', 'writeDataCallback');//关闭数据上传功能
    					window.hilink.writeBLECharacteristicValue(currentDeviceId, serviceUuid, writeUuid, 'FEA90100', 'writeDataCallback');//停止运动
    				}
    			},
                selectType:function(){//改变运动方式之后触发的函数
                    if(currentDeviceId!=null){
                        window.hilink.writeBLECharacteristicValue(currentDeviceId, serviceUuid, writeUuid, 'FEA002020'+app.selected, 'writeDataCallback');//修改设备运动方式
                    }
                }
    		}
		});
	</script>
</body>
</html>